package com.we823.utils.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	public static String getDateString() {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	}

	public static Calendar parse(Date datetime) {
		if (datetime == null) {
			datetime = new Date();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(datetime);
		return calendar;
	}

	public static Integer getYear() {
		return Calendar.getInstance().get(Calendar.YEAR);
	}

	public static Integer getMonth() {
		return Calendar.getInstance().get(Calendar.MONTH)+1;
	}

	public static Integer getDay() {
		return Calendar.getInstance().get(Calendar.DATE);
	}

	public static Integer getMaxDay(int year, int month) {
		if (year > 0 && month > 0) {
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, month);
			return calendar.getMaximum(Calendar.DATE);
		}
		return 31;
	}

	public static String parse(Date date, String format) {
		if(date!=null) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(format);
			return dateFormat.format(date);
		}
		return "";
	}
	
	/**
	 * 计算两个时间之间相差的值，显示为*天*时*分
	 * @param startDate
	 * @param finishDate
	 * @return
	 */
	public static String calculate(Date startDate,Date finishDate) {
		return calculate(startDate, finishDate,1);
	}
	
	/**
	 * 根据type返回不同的形式
	 * @param startDate
	 * @param finishDate
	 * @param type 1：*天*时*分 2：*时*分 3：*分 默认：返回分的总数
	 * @return
	 */
	public static String calculate(Date startDate,Date finishDate,int type) {
		if (startDate==null) {
			return "";
		}
		if (finishDate==null) {
			finishDate = new Date();
		}
		
		long nd = 1000 * 24 * 60 * 60;
	    long nh = 1000 * 60 * 60;
	    long nm = 1000 * 60;
	    
	    long times = finishDate.getTime() - startDate.getTime();
	   String result = "";
	   switch (type) {
	case 1:
		result = String.format("%s天%s时%s分", times/nd, times%nd/nh, times%nd%nh/nm);
		break;
	case 2:
		result = String.format("%s时%s分", times/nh, times%nd%nh/nm);
	case 3:
		result = String.format("%s分", times/nm);
	default:
		result = String.format("%s", times/nm);
		break;
	}
	    return result;
	}
}
